package wxact

import (
	"myproject/wx_test/src/wxglob"
	"strings"
	"time"

	"log"

	"errors"

	"github.com/astaxie/beego/httplib"
)

type accessToken struct {
	AccToken string `json:"access_token"`
	Expires  int    `json:"expires_in"`
}

func GetAccToken() {
	//"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"
	var url []string
	url = append(url, "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=")
	url = append(url, wxglob.Config.Section("wx").Key("appid").String())
	url = append(url, "&secret=")
	url = append(url, wxglob.Config.Section("wx").Key("appsecret").String())
	urls := strings.Join(url, "")

	var exp int
	for {
		if exp-360 > 0 {
			//log.Println(exp)
			//每5分钟检查一次
			exp = exp - 300
			time.Sleep(5 * time.Minute)
		} else {
			var at accessToken
			err := writeAccToken(urls, &at)
			if err != nil {
				log.Println(err)
				return
			}
			log.Println("access token 获取成功")

			exp = at.Expires
			go GetSrvlist()
		}
	}
	return
}

func writeAccToken(urls string, at *accessToken) error {
	//发起get请求，获取参数
	result := httplib.Get(urls).SetTimeout(50*time.Second, 50*time.Second)

	//转换成[]byte
	err := result.ToJSON(at)
	if err != nil {
		log.Println(err)
		return err
	}

	//判断是否解析成功
	if at.AccToken == "" {
		log.Println("access_token 不存在")
		return errors.New("access_token 不存在")
	}

	//储存access_token
	wxglob.AccessToken = at.AccToken

	////把access_token 写入config.ini
	//sec := wxglob.Config.Section("wx")
	//
	////判断key是否存在
	//if sec.HasKey("access_token") {
	//	//如果存在，改变值
	//	sec.Key("access_token").SetValue(at.AccToken)
	//} else {
	//	//如果不存在，创建key
	//	_, err = sec.NewKey("access_token", at.AccToken)
	//	if err != nil {
	//		log.Println(err)
	//		return err
	//	}
	//}
	//
	////＊＊＊保存到config.ini文件
	//wxglob.Config.SaveTo("config.ini")

	return nil
}
